package com.ledi.guns.core.util.baiduUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ledi.guns.core.util.baiduUtil.define.ActionMap;

/**
 * 配置管理器
 *
 * @author hancong03@baidu.com
 */
public final class ConfigManager {

	private static final String configFileName = "config.json";
	private JSONObject jsonConfig = null;
	// 涂鸦上传filename定义
	private final static String SCRAWL_FILE_NAME = "scrawl";
	// 远程图片抓取filename定义
	private final static String REMOTE_FILE_NAME = "remote";
	// 配置信息
	private UEditorConfig uEditorConfig;

	/*
	 * 通过一个给定的路径构建一个配置管理器， 该管理器要求地址路径所在目录下必须存在config.properties文件
	 */
	private ConfigManager(UEditorConfig uEditorConfig) throws IOException {

		this.uEditorConfig = uEditorConfig;
		String configPath = uEditorConfig.getConfig();
		configPath = configPath == null || configPath.isEmpty() ? configFileName : configPath;
		initEnv(configPath);
	}

	/**
	 * 配置管理器构造工厂
	 *
	 * @param uEditorConfig
	 *            配置文件
	 * @return 配置管理器实例或者null
	 */
	public static ConfigManager getInstance(UEditorConfig uEditorConfig) {

		try {
			return new ConfigManager(uEditorConfig);
		} catch (Exception e) {
			System.err.println("UEditor ConfigManager load error~");
			return null;
		}

	}

	// 验证配置文件加载是否正确
	public boolean valid() {

		return jsonConfig != null;
	}

	public JSONObject getAllConfig() {

		return jsonConfig;

	}

	public Map<String, Object> getConfig(int type) {

		Map<String, Object> conf = new HashMap<String, Object>();
		String savePath = null;

		try {
			switch (type) {

				case ActionMap.UPLOAD_FILE:
					conf.put("isBase64", "false");
					conf.put("maxSize", jsonConfig.getLong("fileMaxSize"));
					conf.put("allowFiles", getArray("fileAllowFiles"));
					conf.put("fieldName", jsonConfig.getString("fileFieldName"));
					savePath = jsonConfig.getString("filePathFormat");
					break;

				case ActionMap.UPLOAD_IMAGE:
					conf.put("isBase64", "false");
					conf.put("maxSize", jsonConfig.getLong("imageMaxSize"));
					conf.put("allowFiles", getArray("imageAllowFiles"));
					conf.put("fieldName", jsonConfig.getString("imageFieldName"));
					savePath = jsonConfig.getString("imagePathFormat");
					break;

				case ActionMap.UPLOAD_VIDEO:
					conf.put("maxSize", jsonConfig.getLong("videoMaxSize"));
					conf.put("allowFiles", getArray("videoAllowFiles"));
					conf.put("fieldName", jsonConfig.getString("videoFieldName"));
					savePath = jsonConfig.getString("videoPathFormat");
					break;

				case ActionMap.UPLOAD_SCRAWL:
					conf.put("filename", ConfigManager.SCRAWL_FILE_NAME);
					conf.put("maxSize", jsonConfig.getLong("scrawlMaxSize"));
					conf.put("fieldName", jsonConfig.getString("scrawlFieldName"));
					conf.put("isBase64", "true");
					savePath = jsonConfig.getString("scrawlPathFormat");
					break;

				case ActionMap.CATCH_IMAGE:
					conf.put("filename", ConfigManager.REMOTE_FILE_NAME);
					conf.put("filter", getArray("catcherLocalDomain"));
					conf.put("maxSize", jsonConfig.getLong("catcherMaxSize"));
					conf.put("allowFiles", getArray("catcherAllowFiles"));
					conf.put("fieldName", jsonConfig.getString("catcherFieldName") + "[]");
					savePath = jsonConfig.getString("catcherPathFormat");
					break;

				case ActionMap.LIST_IMAGE:
					conf.put("allowFiles", getArray("imageManagerAllowFiles"));
					conf.put("dir", jsonConfig.getString("imageManagerListPath"));
					conf.put("count", jsonConfig.getInt("imageManagerListSize"));
					break;

				case ActionMap.LIST_FILE:
					conf.put("allowFiles", getArray("fileManagerAllowFiles"));
					conf.put("dir", jsonConfig.getString("fileManagerListPath"));
					conf.put("count", jsonConfig.getInt("fileManagerListSize"));
					break;

			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		conf.put("savePath", savePath);
		conf.put("rootPath", uEditorConfig.getUploadPath());
		conf.put("urlPrefix", uEditorConfig.getUrlPrefix());
		return conf;

	}

	private void initEnv(String configPath) throws IOException {

		String configContent = config();

		try {
			JSONObject jsonConfig = new JSONObject(configContent);
			// 统一url访问前缀
			if (uEditorConfig.getUnified()) {
				Iterator iterator = jsonConfig.keys();
				while (iterator.hasNext()) {
					String key = (String) iterator.next();
					if (key.contains("UrlPrefix")) {
						jsonConfig.put(key, uEditorConfig.getUrlPrefix());
					}
				}
			}
			this.jsonConfig = jsonConfig;
		} catch (Exception e) {
			jsonConfig = null;
		}

	}

	private String[] getArray(String key) throws JSONException {

		JSONArray jsonArray = jsonConfig.getJSONArray(key);
		String[] result = new String[jsonArray.length()];

		for (int i = 0, len = jsonArray.length(); i < len; i++) {
			result[i] = jsonArray.getString(i);
		}

		return result;

	}

	private String readFile(String path) throws IOException {

		StringBuilder builder = new StringBuilder();

		try {
			InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path);
			InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader bfReader = new BufferedReader(reader);

			String tmpContent = null;

			while ((tmpContent = bfReader.readLine()) != null) {
				builder.append(tmpContent);
			}

			bfReader.close();

		} catch (UnsupportedEncodingException e) {
			// 忽略
		}

		return filter(builder.toString());

	}

	// 过滤输入字符串, 剔除多行注释以及替换掉反斜杠
	private String filter(String input) {

		return input.replaceAll("/\\*[\\s\\S]*?\\*/", "");

	}

	private String config() {

		return "{'videoMaxSize':102400000,'videoActionName':'uploadvideo','fileActionName':'uploadfile','fileManagerListPath':'/ueditor/jsp/upload/file/','imageCompressBorder':1600,'imageManagerAllowFiles':['.png','.jpg','.jpeg','.gif','.bmp'],'imageManagerListPath':'/ueditor/jsp/upload/image/','fileMaxSize':51200000,'fileManagerAllowFiles':['.png','.jpg','.jpeg','.gif','.bmp','.flv','.swf','.mkv','.avi','.rm','.rmvb','.mpeg','.mpg','.ogg','.ogv','.mov','.wmv','.mp4','.webm','.mp3','.wav','.mid','.rar','.zip','.tar','.gz','.7z','.bz2','.cab','.iso','.doc','.docx','.xls','.xlsx','.ppt','.pptx','.pdf','.txt','.md','.xml'],'fileManagerActionName':'listfile','snapscreenInsertAlign':'none','scrawlActionName':'uploadscrawl','videoFieldName':'upfile','imageCompressEnable':true,'videoUrlPrefix':'','fileManagerUrlPrefix':'','catcherAllowFiles':['.png','.jpg','.jpeg','.gif','.bmp'],'imageManagerActionName':'listimage','snapscreenPathFormat':'/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}','scrawlPathFormat':'/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}','scrawlMaxSize':2048000,'imageInsertAlign':'none','catcherPathFormat':'/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}','catcherMaxSize':2048000,'snapscreenUrlPrefix':'','imagePathFormat':'/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}','imageManagerUrlPrefix':'','scrawlUrlPrefix':'','scrawlFieldName':'upfile','imageMaxSize':2048000,'imageAllowFiles':['.png','.jpg','.jpeg','.gif','.bmp'],'snapscreenActionName':'uploadimage','catcherActionName':'catchimage','fileFieldName':'upfile','fileUrlPrefix':'','imageManagerInsertAlign':'none','catcherLocalDomain':['127.0.0.1','localhost','img.baidu.com'],'filePathFormat':'/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}','videoPathFormat':'/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}','fileManagerListSize':20,'imageActionName':'uploadimage','imageFieldName':'upfile','imageUrlPrefix':'','scrawlInsertAlign':'none','fileAllowFiles':['.png','.jpg','.jpeg','.gif','.bmp','.flv','.swf','.mkv','.avi','.rm','.rmvb','.mpeg','.mpg','.ogg','.ogv','.mov','.wmv','.mp4','.webm','.mp3','.wav','.mid','.rar','.zip','.tar','.gz','.7z','.bz2','.cab','.iso','.doc','.docx','.xls','.xlsx','.ppt','.pptx','.pdf','.txt','.md','.xml'],'catcherUrlPrefix':'','imageManagerListSize':20,'catcherFieldName':'source','videoAllowFiles':['.mp4','.mp3']}";
	}
}
